package com.gxg.web.Controller;

import com.gxg.common.redis.JedisClient;
import com.gxg.web.dto.PictureCaptchaDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * 图片验证码
 * Created by guxiaoguang on 2018/4/10.
 */
@Api(description = "图片验证码")
@RestController
@RequestMapping("/xuebai/login")
@CrossOrigin(maxAge = 3600)
public class CaptchaController {

    public static final String KEY_TIMESTAMP = "KEY_TIMESTAMP";

    public static final String PICTURE_CAPTCHA = "PICTURE_CAPTCHA_YXC_WEB_";

    public static String preTimestamp = "";

    @Autowired
    JedisClient jedisClient;

    @ApiOperation(value = "获取验证码")
    @RequestMapping(value = "/getCaptcha", method = RequestMethod.POST)
    public Map<String, Object> getCaptchaPicture(@ApiParam(value = "获取验证码") @Valid @RequestBody PictureCaptchaDto dto,
                                                 HttpServletRequest request, HttpServletResponse response) throws IOException {

        Map<String, Object> map = new HashMap<String, Object>();
        // 在内存中创建图象
        int width = 60, height = 30;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取图形上下文
        Graphics g = image.getGraphics();
        // 生成随机类
        Random random = new Random();
        // 设定背景色
        g.setColor(new Color(201 + random.nextInt(50), 201 + random.nextInt(50), 201 + random.nextInt(50)));
        g.fillRect(0, 0, width, height);
        // 设定字体
        g.setFont(new Font("Times New Roman", Font.PLAIN, 28));
        boolean newFlag = true;
        String timestamp = request.getParameter(KEY_TIMESTAMP);
        if (timestamp != null && timestamp.trim().length() > 0) {
            if (timestamp.equals(preTimestamp)) {
                newFlag = false;
            } else {
                preTimestamp = timestamp;
            }
        }

        String uuid;
        // 取随机产生的认证码(4位数字)
        String sRand = "";
        String rand = "";
        if (newFlag) {
            for (int i = 0; i < 4; i++) {
                rand = String.valueOf(random.nextInt(10));
                sRand += rand;
                // 将认证码显示到图象中
                g.setColor(new Color(20 + random.nextInt(111), 20 + random.nextInt(111), 20 + random.nextInt(111)));
                // 调用函数出来的颜色相同，可能是因为种子太接近，以只能直接生成
                g.drawString(rand, 13 * i + 3, 24);
            }

            uuid = UUID.randomUUID().toString();
            System.err.println("sRand : " + sRand);
            jedisClient.set(PICTURE_CAPTCHA + uuid, sRand);
            jedisClient.expire(PICTURE_CAPTCHA + uuid, 3600);// 设置过期时间为60s
            jedisClient.del(PICTURE_CAPTCHA + dto.getPictureToken());

        } else {
            uuid = dto.getPictureToken();
            sRand = jedisClient.get(PICTURE_CAPTCHA + dto.getPictureToken());
            // sRand = (String) session.getAttribute(PICTURE_CAPTCHA);
            for (int i = 0; i < 4; i++) {
                rand = sRand.substring(i, i + 1);
                // 将认证码显示到图象中
                g.setColor(new Color(20 + random.nextInt(111), 20 + random.nextInt(111), 20 + random.nextInt(111)));
                // 调用函数出来的颜色相同，可能是因为种子太接近，以只能直接生成
                g.drawString(rand, 13 * i + 3, 24);
            }
        }

        // 图象生效
        g.dispose();

        String imgData;
        InputStream inputStream = null;
        byte[] data = null;
        try {
            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            ImageOutputStream imOut;
            imOut = ImageIO.createImageOutputStream(bs);
            ImageIO.write(image, "jpg", imOut);
            inputStream = new ByteArrayInputStream(bs.toByteArray());
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        imgData = new String(Base64.encodeBase64(data));
        String base64 = "data:image/jpeg;base64," + imgData;

        map.put("code", "0000");
        map.put("message", "成功");
        map.put("verifyBase64", base64);
        map.put("pictureUuid", uuid);// REDIS图片标识符
        return map;
    }
}